﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls;
using AudioGrabber.Interfaces;
using VkcomAPI.PublicTypes;
using System.IO.IsolatedStorage;

namespace AudioGrabber
{
    public class FileCredentialSaver : ICredentialsHelper
    {
        private IsolatedStorageFile isoFile;
        private ListBox listBox;

        public FileCredentialSaver(ListBox credentialList, IsolatedStorageFile isoFile)
        {
            this.isoFile = isoFile;
            listBox = credentialList;
            listBox.ItemsSource = new List<UserCredentials>();
            if (!isoFile.FileExists("isoFile"))
                isoFile.CreateFile("isoFIle").Close();
        }

        public void SaveToStorage(UserCredentials userCredentials)
        {
            List<UserCredentials> storedEntries = GetAllEntries();
            // Eсли в списке уже есть такие credentials - выходим
            if (!storedEntries.Any(userCred => userCred.Equals(userCredentials)))
                WriteEntry(userCredentials);
        }

        public void SaveToStorage(List<UserCredentials> userCredentials)
        {
            foreach (var userCred in userCredentials)
            {
                WriteEntry(userCred);
            }
        }

        private void WriteEntry(UserCredentials userCredentials)
        {
            using (StreamWriter writer = new StreamWriter(isoFile.OpenFile("isoFile", FileMode.Open)))
            {
                writer.WriteLine(userCredentials.Login);
                writer.WriteLine(userCredentials.Password);
            }
        }

        public List<UserCredentials> GetAllEntries()
        {
            List<UserCredentials> storedEntries = new List<UserCredentials>();
            using (StreamReader reader = new StreamReader(isoFile.OpenFile("isoFile", FileMode.Open)))
                while (!reader.EndOfStream)
                    storedEntries.Add(new UserCredentials(reader.ReadLine(), reader.ReadLine()));
            return storedEntries;
        }

        public void DeleteFromStorage(UserCredentials selectedCredentials)
        {
            List<UserCredentials> storedCredentials = GetAllEntries();
            storedCredentials.Remove(selectedCredentials);
            listBox.Items.Remove(selectedCredentials);
            ResetStorage();
            SaveToStorage(storedCredentials);
            LoadSavedCredentials();
        }

        public delegate void some(ListBoxItem item, UserCredentials userCred);

        public void LoadSavedCredentials()
        {
            //foreach (var userCred in GetAllEntries())
            //    listBox.Items.Add(userCred);
            some s = new some((i,uc) =>
            {
            });
        }



        public void ResetStorage()
        {
            isoFile.OpenFile("isoFile", FileMode.Create).Close();
        }
    }
}
